package com.leyou.auth.interceptors;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.exception.LyException;
import com.leyou.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    private final JwtUtils jwtUtils;

    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {

            //获取cookie中的jwt
            String ly_cookie = CookieUtils.getCookieValue(request, "LY_COOKIE");
            //解析jwt获得载荷信息
            Payload payload = jwtUtils.parseJwt(ly_cookie);

            UserDetail userDetail = payload.getUserDetail();
           // log.info("用户{}正在访问。",userDetail.getUsername());
            // 保存用户

            UserContext.setUser(userDetail);

            return true;

        } catch (Exception e) {
            throw new LyException(401, "JWT无效或过期!", e);

        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 业务结束后，移除用户
        UserContext.removeUser();
    }
}
